<template>
  <div class="page-content">
    <el-card>
      <!--标题区域——start-->
      <el-row style="">
        <el-col :span="22">
          <i class="el-icon-video-camera-solid" style="font-size: 1.625rem; color: #03a9f4"></i>
          <span style="letter-spacing: 0.00625rem">监控设备</span>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" plain @click="addMonitorData">添加设备</el-button>
        </el-col>
      </el-row>
      <!--标题区域——send-->
    </el-card>
    <!-- 表头区域——start -->
    <table-bar :columns="columns" @changeColumn="changeColumn" style="margin-top: 1.5625rem">
      <div slot="top">
        <el-form label-width="4.375rem" :model="conditionData">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="使用场景" label-width="5.625rem">
                <el-select v-model="typeValue" placeholder="请选择" @change="changeType">
                  <el-option v-for="item in conditionTypeOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="6" v-if="isfeedingMachine">
              <el-form-item label="鸽棚编号" label-width="5.625rem">
                <el-select v-model="dovecoteNumberValue" placeholder="请选择" @change="changeDovecoteNumber">
                  <el-option v-for="item in conditiondovOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="设备状态" label-width="5.625rem">
                <el-select v-model="statusCodeValue" placeholder="请选择" @change="changeStatusCode">
                  <el-option v-for="item in statusCodeOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="6" style="float: right; margin-right: 0.625rem">
              <el-button type="primary" @click="searchMonitor()">搜索</el-button>
              <el-button @click="reset">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-tooltip slot="button1" effect="dark" content="切换显示" placement="top-start">
        <el-button icon="el-icon-menu" size="small" @click="cutShow()" />
      </el-tooltip>
    </table-bar>
    <!-- 表头区域——end -->
    <!--主体内容区域——start-->
    <el-row>
      <el-row style="margin-bottom: 0">
        <el-col style="
                        font-size: 1rem;
                        font-weight: bold;
                        letter-spacing: 0.0625rem;
                    " :span="15">
          <i class="el-icon-s-order"></i>
          <!-- 设备数量:{{ total }}台 -->
          设备数量:{{ 5 }}台
        </el-col>
      </el-row>

      <!--设备信息列表区域——start-->
      <el-row style="margin-bottom: 0">
        <the-table v-if="!isShowList" :data="monitorList" style="font-size: 0.875rem">
          <el-table-column prop="dovecoteNumber" label="鸽棚编号" min-width></el-table-column>
          <el-table-column prop="type" label="使用场景" min-width show-overflow-tooltip></el-table-column>
          <el-table-column prop="monitoringLocation" label="摄像头监控位置" min-width show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="deviceSerial" label="设备序列号" min-width></el-table-column>
          <el-table-column prop="validateCode" label="设备验证码" min-width></el-table-column>
          <el-table-column prop="createBy" label="创建者" min-width show-overflow-tooltip></el-table-column>
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.statusCode" :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#dcdfe6" @change="changeCode(scope.row, $event)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-video-play" @click="playMonitor(scope.row)">
                播放
              </el-button>
              <el-button type="text" icon="el-icon-edit" @click="upDateMonitorData(scope.row)">
                编辑
              </el-button>
              <el-button type="text" style="color: #fa6962" icon="el-icon-delete" @click="delMonitorData(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </the-table>
      </el-row>
      <!--设备信息列表区域——end-->
    </el-row>
    <!-- 视频展示——start -->
    <div v-if="isShowList" style="margin-top: 0.625rem; display: flex; flex-wrap: wrap">
      <!-- <el-card
                style="
                    width: 30rem;
                    height: 30rem;
                    font-size: 1.2rem;
                    margin-right: 1rem;
                    margin-top: 1rem;
                "
                v-for="(item, index) in monitorList"
                :key="index"
            >
                <div
                    slot="header"
                    class="clearfix"
                    style="width: 100%; text-align: center"
                >
                    位置: {{ item.monitoringLocation }}
                </div>
                <ezuiKit :monitorData="item" class="text item" />
            </el-card> -->
      <el-card style="
                    width: 30rem;
                    height: 30rem;
                    font-size: 1.2rem;
                    margin-right: 1rem;
                    margin-top: 1rem;
                " v-for="(item1, index1) in vedioUrl" :key="index1 + 'vedio'">
        <div slot="header" class="clearfix" style="width: 100%; text-align: center">
          位置:监控视频
        </div>
        <ezuiKitTwo :vedioUrl="item1" class="text item" />
      </el-card>
    </div>
    <!-- 视频展示——end -->
    <!-- 分页——start -->
    <el-pagination :page-sizes="[6, 12, 18, 24]" :page-size="monitorPageSize" :current-page="monitorPageNum" layout="total, sizes, prev, pager, next, jumper" :total="total" class="page" v-show="pageShow" @current-change="handleCurrentChange" @size-change="handleSizeChange">
    </el-pagination>
    <!-- 分页——end -->
    <!--主体内容区域——end-->
    <!-- 摄像头对话框——start -->
    <el-dialog title="监控视频" customClass="customWidth" :visible.sync="monitorDialogTableVisible" style="text-align: center; width: 70%; margin: 0 auto" @close="closeMonitorDialog()" ref="currentMonitorDialog" append-to-body>
      <ezui-kit :monitorData="monitorData" />
    </el-dialog>
    <!-- 摄像头对话框——end -->
    <!-- 编辑摄像头信息对话框——start -->
    <upDateMonitorInfo :dialogVisible="monitorDataDialogTableVisible" :monitorinfo="originalMonitorInfo" :isUpdate="isUpdate" @closeDialog="closeDialog" @inputInfo="inputInfo"></upDateMonitorInfo>
    <!-- 编辑摄像头信息对话框——end -->
  </div>
</template>

<script>
import { mapState } from 'vuex'
import {
  getAllMonitor,
  upDate,
  deleteMonitor,
  addMonitor,
  changeStatusCode,
} from '../../api/Video/VideoManage.js'
import upDateMonitorInfo from '.././../components/video/upDateMonitorInfo.vue'
const ezuiKit = () => import('../../components/video/EZUIKitJs.vue')
import ezuiKitTwo from '../../components/video/EZUIKitJsTwo.vue'
export default {
  name: 'VideoManage',
  meta: {
    title: '视频管理',
  },
  data() {
    return {
      monitorPageNum: 1, //获取分页摄像头参数
      monitorPageSize: 6, //获取分页摄像头参数
      getAllMonitorParams: {
        baseId: '',
      },
      isShowList: true, //列表展示
      monitorList: [], //摄像头列表
      total: 0, //摄像头设备总数
      pageShow: true, //分页显示
      player: '',
      columns: [
        //表格列目筛选
        {
          name: '序号',
          show: true,
        },
        {
          name: '创建者',
          show: true,
        },
        {
          name: '基地名称',
          show: true,
        },
        {
          name: '鸽棚编号',
          show: true,
        },
        {
          name: '摄像头监控位置',
          show: true,
        },
        {
          name: '创建时间',
          show: true,
        },
        {
          name: '状态',
          show: true,
        },
        {
          name: '操作',
          show: true,
        },
      ],
      monitorDialogTableVisible: false, //监控视频对话框是否显示
      monitorData: null, //监控视频数据
      currentMonitorId: '', //当前播放的摄像头id
      currentPlayer: null, //弹框里当前播放的摄像头
      currentMonitorDialog: '', //弹框
      isUpdate: false, //摄像头信息对话框组件是否用于更新信息
      monitorDataDialogTableVisible: false, //摄像头信息对话框
      originalMonitorInfo: null, //摄像头原有信息
      originalId: '', //摄像头id
      conditionTypeOptions: [
        //摄像头使用场景下拉框    //条件查询相关数据start
        {
          value: '1',
          label: '基地',
        },
        {
          value: '2',
          label: '鸽棚',
        },
        {
          value: '3',
          label: '投喂机',
        },
        {
          value: '4',
          label: '其他',
        },
      ],
      statusCodeOptions: [
        //设备使用状态
        {
          value: '3',
          label: '全部',
        },
        {
          value: '0',
          label: '未启用',
        },
        {
          value: '1',
          label: '使用中',
        },
        {
          value: '2',
          label: '故障',
        },
      ],
      typeValue: '1', //使用场景下拉框值
      dovecoteNumberValue: '全部', //鸽棚编号下拉框值
      statusCodeValue: '3', //设备下拉框值
      isfeedingMachine: false, //是否摄像头使用场景为投喂机
      isPlay: false,
      searchAll: true,
      vedioUrl: [
        // {
        //     id: 1,
        //     url: "https://open.ys7.com/v3/openlive/G24611150_1_1.m3u8?expire=1677221563&id=418782647438213120&t=f908ee01596a9fbfe300e2642befb711fad590d28d6d6b2d7f0caa0231ce61fb&ev=100",
        // },
        // {
        //     id: 2,
        //     url: "https://open.ys7.com/v3/openlive/G24611150_2_2.m3u8?expire=1677221669&id=418783091427762176&t=4682d07b92ae8177996861f5d3bcc8f12c50164d57533e51d77f0dca2f43c82d&ev=100",
        // },
        {
          id: 3,
          url: 'http://hls01open.ys7.com/openlive/cea05ef872524765bc734e6fc5bb382b.hd.m3u8',
        },
        {
          id: 4,
          url: 'http://hls01open.ys7.com/openlive/e0b2597699cd4e4cbb0f2043e769bce2.hd.m3u8',
        },
        {
          id: 5,
          url: 'http://hls01open.ys7.com/openlive/a954a2aa526f449c8cc92e3a8f8a84c4.hd.m3u8',
        },
        {
          id: 6,
          url: 'http://hls01open.ys7.com/openlive/cc61a0e61a4145fe97573e6adda76d50.hd.m3u8',
        },
        {
          id: 7,
          url: 'http://hls01open.ys7.com/openlive/2929fb95448f496d98a964d09a9b43f9.hd.m3u8',
        },
      ],
    }
  },
  computed: {
    ...mapState({
      baseInfo: (
        state //基地信息
      ) => state.Usersetting.BaseInfo,
      allDovecoteInfo: (
        state //基地所有鸽棚信息
      ) => state.Usersetting.AllDovecoteInfo,
    }),
    conditionData() {
      return {
        //条件查询数据
        baseId: this.baseInfo.id, //基地id
        type: '', //摄像头类型
        dovecoteNumber: '', //鸽棚编号
        statusCode: '', //设备状态
      }
      // get: function() {
      //     let data = {
      //         //条件查询数据
      //         baseId: this.baseInfo.id, //基地id
      //         type: "", //摄像头类型
      //         dovecoteNumber: "", //鸽棚编号
      //         statusCode: "", //设备状态
      //     }
      //     return data
      // },
      // set: function(val) {
      //     console.log('我在computed里面')
      //     console.log(val);
      //     this.conditionData.type = val.type;
      //     this.conditionData.dovecoteNumber = val.dovecoteNumber;
      //     this.conditionData.statusCode = val.statusCode;
      // }
    },
    conditiondovOptions() {
      //鸽棚选择下拉框的options
      let options = [
        {
          value: '全部', //选择所有鸽棚的投喂机
          label: '全部',
        },
      ]
      this.allDovecoteInfo.forEach((item, index) => {
        let tempItem = {
          value: '',
          label: '',
        }
        tempItem.value = item.dovecoteNumber
        tempItem.label = item.dovecoteNumber
        options.push(tempItem)
      })
      return options
    },
  },
  created() {
    if (this.baseInfo.id) {
      this.getAllMonitorData()
    }
  },
  mounted() {},
  components: {
    upDateMonitorInfo,
    ezuiKit,
    ezuiKitTwo,
  },
  methods: {
    closePlayer() {
      this.player.stop().then(() => {
        // console.log("执行播放成功后其他动作");
      })
    },
    //获得摄像头列表
    async getAllMonitorData() {
      let that = this
      // console.log("我在获取所有摄像头设备信息");
      // console.log(that.baseInfo.id)
      this.getAllMonitorParams.baseId = this.baseInfo.id
      // console.log(this.getAllMonitorParams);

      let { data } = await getAllMonitor(
        this.monitorPageNum,
        this.monitorPageSize,
        this.getAllMonitorParams
      )
      // console.log("数据", data);

      if (data.statusCode != 20000) {
        return this.$message.error('获取数据失败！')
      } else {
        // this.$message({
        //     message: "获取数据成功！",
        //     type: "success",
        // });
      }
      // console.log(data.data.total);
      // console.log("end");

      let list = data.data.records
      this.total = data.data.total
      list.forEach((item) => {
        if (item.type == 1) {
          item.type = '基地'
        } else if (item.type == 2) {
          item.type = '鸽棚'
        } else if (item.type == 3) {
          item.type = '投喂机'
        } else {
          item.type = '其他'
        }
      })
      this.monitorList = list
      // console.log("修改后");
      console.log('数据', this.monitorList)
    },
    iFrameHeight() {
      // console.log("执行");
      var ifm = document.getElementById('iframeHome')
      var subWeb = document.frames ? document.frames['iframeHome'].document : ifm.contentDocument
      if (ifm != null && subWeb != null) {
        ifm.height = subWeb.body.scrollHeight
        ifm.width = subWeb.body.scrollWidth
      }
    },

    //切换显示
    cutShow() {
      this.isShowList = !this.isShowList
      this.pageShow = !this.pageShow
    },

    //改变分页当前页码
    handleCurrentChange(newPage) {
      this.monitorPageSize = newPage
      this.getAllMonitor()
    },

    //改变分页显示条数
    handleSizeChange(newSize) {
      this.monitorPageNum = newSize
      this.getAllMonitor()
    },

    //表格数据筛选
    changeColumn(columns) {
      this.columns = columns
      this.$refs.table.doLayout()
    },

    //修改设备状态
    async changeCode(row, $event) {
      let that = this
      // console.log("修改状态");
      // console.log($event); //switch现在的状态
      let action = '关闭' //用户进行的操作
      if ($event) {
        action = '开启'
      }
      //    $event = !$event
      //    console.log($event)
      this.$confirm('确定' + action + '摄像头?')
        .then(async () => {
          let { data } = await changeStatusCode(row.id, $event)
          // console.log(data);
          if (data.statusCode === 20000) {
            return this.$message({
              message: action + '摄像头成功！',
              type: 'success',
            })
          } else {
            return this.$message.error(action + '摄像头失败！')
          }
        })
        .catch(async () => {
          row.statusCode = 0
          // this.getAllMonitorData();
        })
    },

    //播放视频
    playMonitor(row) {
      console.log(row)
      this.monitorDialogTableVisible = true
      this.monitorData = row
      this.isPlay = true //将iframe组件插入，播放视频
      // console.log("我在播放视频");
    },

    //关闭视频对话框
    closeMonitorDialog() {
      this.monitorUrl = ''
      this.monitorDialogTableVisible = false
      this.isPlay = true //将iframe组件去除，实现关闭
    },

    //更新摄像头信息
    upDateMonitorData(row) {
      // console.log("我在更新摄像头信息");
      // console.log(row);
      this.isUpdate = true
      this.originalMonitorInfo = row
      this.originalId = row.id
      // console.log(this.originalId);
      this.monitorDataDialogTableVisible = true
    },

    //关闭更新摄像头信息的对话框
    closeDialog() {
      console.log('关闭')
      this.$confirm('确认关闭？')
        .then(() => {
          this.monitorDataDialogTableVisible = false
          this.isUpdate = false
          // console.log(this.isUpdate);
        })
        .catch(() => {})
    },

    //提交摄像头信息(包括修改和添加)
    async inputInfo(info) {
      let data = {}
      // console.log("提交修改",info.statusCode);
      info.statusCode = info.statusCode.toString()
      if (this.isUpdate) {
        //判断是添加摄像头还是修改
        let data = info
        delete data.templete
        delete data.url
        delete data.accessToken
        let res = await upDate(this.originalId, data)
        // console.log('结果',res)
        data = res.data
        if (data.statusCode === 20000) {
          this.monitorDataDialogTableVisible = false //关闭修改对话框
          this.$message({
            message: '修改成功！',
            type: 'success',
          })
          this.getAllMonitorData()
          this.isUpdate = !this.isUpdate
          return
        } else {
          return this.$message.error('修改失败！')
        }
      } else {
        // console.log("我在添加设备");
        // console.log(info);
        let res = await addMonitor(info)
        data = res.data
        // console.log(data);

        if (data.statusCode === 20000) {
          this.monitorDataDialogTableVisible = false //关闭修改对话框
          this.$message({
            message: '修改成功！',
            type: 'success',
          })
          this.getAllMonitorData()
          this.isUpdate = !this.isUpdate
          return
        } else {
          return this.$message.error('修改失败！')
        }
      }
    },

    //删除摄像头
    async delMonitorData(row) {
      let that = this
      that
        .$confirm('确认删除？')
        .then(async () => {
          // console.log("我在删除");
          // console.log(row);
          // console.log(row.id);
          let { data } = await deleteMonitor(row.id)
          // console.log(data);

          if (data.statusCode === 20000) {
            if (this.searchAll) {
              this.getAllMonitorData()
            } else {
              this.searchMonitor()
            }
            return that.$message({
              message: '删除成功！',
              type: 'success',
            })
          } else {
            return that.$message.error('删除失败！')
          }
        })
        .catch(() => {
          return that.$message('取消删除')
        })
    },

    //添加摄像头
    addMonitorData() {
      let that = this
      that.monitorDataDialogTableVisible = true
    },

    //摄像头条件查询部分
    //改变摄像头类型
    changeType(type) {
      // console.log("改变了");
      // if (type === "1") {
      // console.log(this.conditionData.type);
      // }
      if (type === '3') {
        this.isfeedingMachine = true
        // console.log(this.isfeedingMachine);
      } else {
        this.isfeedingMachine = false
      }
    },

    //改变鸽棚编号
    changeDovecoteNumber(dovecoteNumber) {
      // console.log("鸽棚状态改变");
    },

    //改变摄像头状态
    changeStatusCode(value) {
      // console.log("摄像头状态代表");
      // console.log(value);
    },

    //搜索相关设备
    async searchMonitor() {
      let that = this
      that.conditionData.type = that.typeValue //本来可以合并，只用conditionData绑定就好，但是由于一些参数传参时会删去，直接使用绑定重置后默认值会出错
      that.conditionData.dovecoteNumber = that.dovecoteNumberValue
      that.conditionData.statusCode = that.statusCodeValue
      // console.log(that.conditionData);
      if (that.isfeedingMachine) {
        //分两种情况（使用场景是否为投喂机）
        //条件查询不完善，
        if (that.conditionData.type === '' || that.conditionData.statusCode === '') {
          return that.$message({
            message: '请完善你的选择',
            type: 'warning',
          })
        }
      } else {
        //条件查询不完善，
        if (that.conditionData.type === '' || that.conditionData.statusCode === '') {
          return that.$message({
            message: '请完善你的选择',
            type: 'warning',
          })
        }
        //条件完善，此时参数里不需要dovecoteNumber
        delete that.conditionData.dovecoteNumber
      }

      //当设备状态为全部时，则不用传设备状态参数
      if (that.conditionData.statusCode === '3') {
        delete that.conditionData.statusCode
      }

      //当选择的是投喂机且鸽棚为全部的话，去掉鸽棚
      if (that.isfeedingMachine) {
        if (that.conditionData.dovecoteNumber === '全部') {
          delete that.conditionData.dovecoteNumber //删除鸽棚编号这一参数
        }
      }
      // console.log("最终参数");
      // console.log(that.conditionData);
      that.monitorPageNum = 1
      that.monitorPageSize = 6
      let { data } = await getAllMonitor(
        that.monitorPageNum,
        that.monitorPageSize,
        that.conditionData
      )
      // console.log("条件查询");
      // console.log(data);
      // console.log(that.conditionData)

      if (data.statusCode != 20000) {
        return that.$message.error('获取数据失败！')
      } else {
        this.searchAll = false
        that.$message({
          message: '获取数据成功！',
          type: 'success',
        })
        let list = data.data.records
        that.total = data.data.total
        list.forEach((item) => {
          if (item.type == 1) {
            item.type = '基地'
          } else if (item.type == 2) {
            item.type = '鸽棚'
          } else if (item.type == 3) {
            item.type = '投喂机'
          } else {
            item.type = '其他'
          }
        })
        that.monitorList = list
      }
    },

    //重置条件查询
    reset() {
      this.typeValue = '1' //本来可以合并，只用conditionData绑定就好，但是由于一些参数传参时会删去，直接使用绑定重置后默认值会出错
      this.dovecoteNumberValue = '全部'
      this.statusCodeValue = '3'
      this.conditionData.type = ''
      this.conditionData.dovecoteNumber = ''
      this.conditionData.statusCode = ''
    },
  },
}
</script>

<style lang="scss" scoped>
.page-content {
  .page {
    margin-top: 1.25rem;
    text-align: center;
  }
  .customWidth {
    width: 40%;
  }
}
</style>